package odgs.message;

import odgs.Connection;
import odgs.listener.MessageListener;
import odgs.listener.NetworkManagerListener;
import odgs.manager.DataManager;
import odgs.manager.ExecuteManager;
import odgs.manager.NetworkManager;
import odgs.manager.ResourceManager;
import odgs.manager.ServerManager;
import odgs.manager.TransactionManager;
import odgs.message.server.NullMessageHandler;

public class ServerMessageProcessor implements MessageProcessor, NetworkManagerListener, MessageListener
{
	private ServerManager	serverManager;
	private NetworkManager	networkManager;

	public void setNetworkManager(NetworkManager networkManager)
	{
		this.networkManager = networkManager;
		this.networkManager.addNetworkManagerListener(this);
	}

	public void setServerManager(ServerManager serverManager)
	{
		this.serverManager = serverManager;
	}

	//NetworkManagerListener
	public void connected(Connection con)
	{
		con.addMessageListener(this);
	}
	
	//NetworkManagerListener
	public void disconnected(Connection con)
	{
		con.removeMessageListener(this);
	}

	public void connectedServer(Connection connection){}
	public void disconnectedServer(Connection con){}
	public void error(int error){}
	public void opened(int port){}

	public void received(Connection source, Message msg)
	{
		MessageHandler handler = getHandler(msg);
		handler.execute(this, msg, source);
	}

	public MessageHandler getHandler(Message msg)
	{
		String path = "odgs.message.server." + msg.getName() + "Handler";
		serverManager.log("System Log : " + path);
		Class clazz;
		try 
        {
			clazz = Class.forName(path);
			return (MessageHandler) clazz.newInstance();
		}
        catch (Exception e) 
        {
        	return new NullMessageHandler(path);
        }
	}
	public void sended(Connection source, Message msg){}

	public ServerManager getServerManager()
	{
		return serverManager;
	}

	public DataManager getDataManager()
	{
		return null;
	}

	public NetworkManager getNetworkManager()
	{
		return networkManager;
	}

	public TransactionManager getTransactionManager()
	{
		return null;
	}

	public ResourceManager getResourceManager()
	{
		return null;
	}

	public ExecuteManager getExecuteManager()
	{
		return null;
	}
}
